/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.view.list;

import javax.faces.event.ActionEvent;

/**
 *
 * @author Walter Lütgenau
 */
public class ListPager implements Pager {
    public static final int DEFAULT_PAGE_SIZE = 20;

    PageableList list;
    
    public ListPager(PageableList list) {        
        this.list = list;
        list.setPageSize(DEFAULT_PAGE_SIZE);
    }

    public PageableList getList() {
        return list;
    }

    public boolean isPagingRequired() {
        return list.getTotalSize() > list.getPageSize();
    }

    public void first() {
        list.setPageStart(0);
    }
    
    public void first(ActionEvent e) {
        first();
    }

    public int getPageSize() {
        return list.getPageSize();
    }

    public void last() {
        int page = (list.getTotalSize()-1)/list.getPageSize();
        if ( page < 0)
            return;
        list.setPageStart(page*list.getPageSize());
    }
    
    public void last(ActionEvent e) {
        last();
    }

    public void next() {
        int start = list.getPageStart();
        if ( start + list.getPageSize() > list.getTotalSize()) {
            list.setPageStart(start);
            return;
        }
        
        list.setPageStart(start + list.getPageSize());
    }
    
    public void next(ActionEvent e) {
        next();
    }

    public void previous() {
        int start = list.getPageStart();
        if ( start - list.getPageSize() < 0) {
            list.setPageStart(start);
            return;
        }
        
        list.setPageStart(start - list.getPageSize());
    }
    
    public void previous(ActionEvent e) {
        previous();
    }

    public void setPageSize(int size) {
        list.setPageSize(size);
    }
}
